package controllers

import (
	"github.com/astaxie/beego"
	"xiaoercaidan/socketCenter/scoket"
	"github.com/astaxie/beego/httplib"
	"encoding/json"
	"xiaoercaidan/publicResources/models"
	"time"
	"strconv"
	"github.com/qiniu/api.v7/storage"
	"github.com/qiniu/api.v7/auth/qbox"
	"fmt"
	"context"
	"bytes"
)

// Operations about Users
type WxSocket struct {
	beego.Controller
}

var (
	//设置上传到的空间
	bucket = "snso"
	ACCESS_KEY = "YwUhM_hu__HQUxmwdOCCEASoQbEqrExHNcOuBF_F"
	SECRET_KEY = "sTvSUv3A8uSI7lQ58mYG4AnCZxOeoKy3z9V7xjOq"
)






// @Title SendMessage
// @Description  发起呼叫
// @Param 	shopId		body 	string	true		"店铺"
// @Param 	table		body 	string	true		"桌台".
// @Param 	url		body 	string	true		"服务url"
// @Param 	ringContent		body 	string	true		"服务内容txt"
// @Param 	ringType		body 	string	true		"服务类型"
// @Param   userId     patch int64   true int64       "用户ID"
// @Param   token     patch string   true string       "token"
// @Param   timeStamp     patch int64   true int64       "时间戳"
// @router /ring [get]
func (this *WxSocket) Ring() {

	var BaseResult = new(models.BaseResult)

	//userId, _ := this.GetInt64("userId", 0)
	//timeStamp, _ := this.GetInt64("timeStamp", 0)
	//token := this.GetString("token")

	shopId := this.GetString("shopId")
	table := this.GetString("table")
	url := this.GetString("url")
	ringContent := this.GetString("ringContent")
	ringType, _ := this.GetInt8("ringType", 0)

	//if (userId <= 0 || timeStamp <= 0 || len(token) <= 0 ) {
	//	BaseResult.Code = 100
	//	BaseResult.Msg = "身份验证错误"
	//} else
	if ( len(shopId) <= 0 || len(table) <= 0 || len(url) <= 0 || len(ringContent) <= 0 || ringType <= 0) {
		BaseResult.Code = 100
		BaseResult.Msg = "参数不全"
	} else {

		//url := "http://" + beego.AppConfig.String("basehost") + ":" + beego.AppConfig.String("baseport") + "/v1/apis/user/userTokenVeri"
		//fmt.Println(url)
		//
		//req := httplib.Get(url)
		//
		//resp, err := req.String()
		//
		//if (err == nil) {
		//	var mapStr = make(map[string]interface{})
		//
		//	json.Unmarshal([]byte(resp), &mapStr)
		//
		//	if (mapStr["code"].(float64) == 0) {
		//		BaseResult.Data = socket.RingPush(shopId, table, ringContent, url, ringType)
		//	} else {
		//
		//		BaseResult.Code = int32(mapStr["code"].(float64))
		//		BaseResult.Msg = mapStr["msg"].(string)
		//	}
		//
		//} else {
		//	BaseResult.Code = 100
		//	BaseResult.Msg = "服务异常"
		//	this.Data["json"] = BaseResult
		//}
		BaseResult.Data = socket.RingPush(shopId, table, ringContent, url, ringType)

	}

	this.Data["json"] = BaseResult

	this.ServeJSON()

}



// @Title SpeechConversion
// @Description  语音转换
// @Param  tex	必填	合成的文本，使用UTF-8编码。小于512个中文字或者英文数字。（文本在百度服务器内转换为GBK后，长度必须小于1024字节）
// @Param tok	必填	开放平台获取到的开发者access_token（见上面的“鉴权认证机制”段落）
// @Param cuid	必填	用户唯一标识，用来区分用户，计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码，长度为60字符以内
// @router /speechConversion [get]
func (this *WxSocket)SpeechConversion() {

	tex := this.GetString("tex")
	cuid := this.GetString("cuid")
	tok := this.GetString("tok")

	req := httplib.Get("http://tsn.baidu.com/text2audio")
	req.Param("tex", tex)
	req.Param("tok", tok)
	req.Param("cuid", cuid)

	req.Param("ctp", "1")
	req.Param("lan", "zh")
	req.Param("spd", "3")
	req.Param("pit", "5")
	req.Param("vol", "10")
	req.Param("per", "0")

	resp, err := req.String()

	var BaseResult = new(models.BaseResult)

	if (err == nil) {
		var mapStr map[string]interface{}

		json.Unmarshal([]byte(resp), &mapStr)

		if _, ok := mapStr["err_detail"]; &mapStr != nil &&  ok {

			BaseResult.Code = 100

			BaseResult.Msg = mapStr["err_detail"].(string)

		} else {

			var fileName = strconv.FormatInt(time.Now().UnixNano(), 10) + ".ogg"

			var data = []byte(resp)

			err := QiniuUpload(data, fileName)

			if (err != nil) {
				BaseResult.Msg = err.Error()
				BaseResult.Code = 100
			} else {

				var image = new(models.File)
				image.FileName = fileName
				image.FilePath = "http://omjjy36ny.bkt.clouddn.com/" + image.FileName
				image.FileSize = int64(len(data))
				BaseResult.Data = image

			}


			//var path string
			//
			//if beego.AppConfig.String("runmode") == "prod" {
			//	path = "/files/ring/"
			//} else {
			//	path = "/static/file/"
			//}
			//
			//fmt.Println(path)
			//
			//if err := ioutil.WriteFile(path + fileName, []byte(resp), 0644); err == nil {
			//
			//	var resultMap map[string]interface{} = make(map[string]interface{})
			//
			//	resultMap["url"] = "http://" + beego.AppConfig.String("httphost") + ":" + beego.AppConfig.String("httpport") + path + fileName
			//	BaseResult.Data = resultMap
			//} else {
			//	BaseResult.Code = 100
			//	BaseResult.Msg = "语音文件写入异常"
			//}

		}

	} else {

	}

	this.Data["json"] = BaseResult
	this.ServeJSON()

}

func QiniuUpload(data []byte, fileName string) (error) {

	putPolicy := storage.PutPolicy{
		Scope:               bucket,
	}

	mac := qbox.NewMac(ACCESS_KEY, SECRET_KEY)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuanan
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	// 可选配置
	putExtra := storage.PutExtra{
		Params: map[string]string{
			//"x:name": "github logo",
		},
	}


	//f.Read(data)

	dataLen := int64(len(data))

	var key = fileName

	//var key  =strconv.FormatInt(time.Now().Unix(), 10)

	err := formUploader.Put(context.Background(), &ret, upToken, key, bytes.NewReader(data), dataLen, &putExtra)
	fmt.Println(ret.Key, ret.Hash)

	return err
}



